package com.ruoyi.management.base.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class TemplateMessageSender {
    private static final Logger logger = LoggerFactory.getLogger(TemplateMessageSender.class);

    /**
     * 发送模板消息
     */
    public static void sendTemplateMessage(String accessToken, String toUserOpenId,
                                           String templateId, String url,
                                           Map<String, TemplateData> data) {
        // 1. 构建JSON请求体（使用fastjson更安全）
        JSONObject requestBody = new JSONObject();
        requestBody.put("touser", toUserOpenId);
        requestBody.put("template_id", templateId);
        requestBody.put("url", url);

        JSONObject dataJson = new JSONObject();
        data.forEach((key, templateData) -> {
            JSONObject item = new JSONObject();
            item.put("value", templateData.getValue());
            item.put("color", templateData.getColor());
            dataJson.put(key, item);
        });
        requestBody.put("data", dataJson);

        // 2. 验证access_token有效性
        if (accessToken == null || accessToken.contains("errcode")) {
            logger.error("无效的access_token: {}", accessToken);
            throw new IllegalArgumentException("无效的access_token");
        }

        // 3. 发送请求
        String messageUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        System.out.println(messageUrl);
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost request = new HttpPost(messageUrl);
            request.setHeader(new BasicHeader("Content-Type", "application/json; charset=UTF-8"));
            request.setEntity(new StringEntity(requestBody.toJSONString(), "UTF-8"));

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                String result = EntityUtils.toString(response.getEntity());
                JSONObject resultJson = JSON.parseObject(result);

                if (resultJson.getIntValue("errcode") != 0) {
                    logger.error("发送模板消息失败: {}", result);
                    throw new RuntimeException("微信接口返回错误: " + resultJson.getString("errmsg"));
                }

                logger.info("模板消息发送成功: {}", result);
            }
        } catch (Exception e) {
            logger.error("发送模板消息异常", e);
            throw new RuntimeException("发送模板消息失败", e);
        }
    }


    public static class TemplateData {
        private String value;
        private String color;

        // getters and setters
        public String getValue() { return value; }
        public void setValue(String value) { this.value = value; }
        public String getColor() { return color; }
        public void setColor(String color) { this.color = color; }
    }


}